<!DOCTYPE html>
<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Unity WebGL Player | catchthechick</title>
    <link rel="shortcut icon" href="TemplateData/favicon.ico">
    <link rel="stylesheet" href="TemplateData/style.css">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="format-detection" content="telephone=no">

    <!-- force webkit on 360 -->
    <meta name="renderer" content="webkit"/>
    <meta name="force-rendering" content="webkit"/>
    <!-- force edge on IE -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="msapplication-tap-highlight" content="no">

    <!-- force full screen on some browser -->
    <meta name="full-screen" content="yes"/>
    <meta name="x5-fullscreen" content="true"/>
    <meta name="360-fullscreen" content="true"/>

    <script src="../../Plugins/ShakePlugin.jslib"></script>
    
    <script src="https://telegram.org/js/telegram-web-app.js"></script>
    <script src="https://unpkg.com/@tonconnect/sdk@latest/dist/tonconnect-sdk.min.js"></script>
    <script src="https://unpkg.com/@tonconnect/ui@latest/dist/tonconnect-ui.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/tonweb@latest/dist/tonweb.min.js"></script>
    <!-- <script src="https://cdn.jsdelivr.net/npm/@tonclient/core@latest/dist/tonclient-core.min.js"></script> -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/@tonclient/lib-web@latest/dist/tonclient-lib-web.min.js"></script> -->
    <!-- <script src="//cdn.bootcss.com/vConsole/3.3.4/vconsole.min.js"></script> -->

    <script src="https://sad.adsgram.ai/js/sad.min.js"></script>
    <script src="../../Plugins/AdsGramPlugin.jslib"></script>
    <style>
    body {
      height: 100vh;
      overflow: hidden;
    }
    </style>
    
  </head>
  <body>
    <div id="ton-connect"></div>
    <div id="unity-container" class="unity-desktop">
      <canvas id="unity-canvas" width=1080 height=2400></canvas>
      <div id="unity-loading-bar">
        <div id="unity-logo"></div>
        <div id="unity-progress-bar-empty">
          <div id="unity-progress-bar-full"></div>
        </div>
      </div>
      <div id="unity-warning"> </div>
      <div id="unity-footer">
        <div id="unity-webgl-logo"></div>
        <div id="unity-fullscreen-button"></div>
        <div id="unity-build-title">catchthechick</div>
      </div>
    </div>
    
    <script>
      var gameInstance = null;

      // 扩张到最大
      Telegram.WebApp.expand();
      Telegram.WebApp.disableVerticalSwipes();
      Telegram.WebApp.isClosingConfirmationEnabled = true;
      var container = document.querySelector("#unity-container");
      var canvas = document.querySelector("#unity-canvas");
      var loadingBar = document.querySelector("#unity-loading-bar");
      var progressBarFull = document.querySelector("#unity-progress-bar-full");
      var fullscreenButton = document.querySelector("#unity-fullscreen-button");
      var warningBanner = document.querySelector("#unity-warning");

      const tonConnectUI = new TON_CONNECT_UI.TonConnectUI({
        manifestUrl: 'https://catchthechick.com/assets/manifest.json',
        buttonRootId: 'ton-connect',
        network: 'mainnet',//testnet
        modal: true,
      });

      tonConnectUI.uiOptions = {
          twaReturnUrl: 'https://t.me/durov'
      };

      // Shows a temporary message banner/ribbon for a few seconds, or
      // a permanent error message on top of the canvas if type=='error'.
      // If type=='warning', a yellow highlight color is used.
      // Modify or remove this function to customize the visually presented
      // way that non-critical warnings and error messages are presented to the
      // user.
      function unityShowBanner(msg, type) {
        function updateBannerVisibility() {
          warningBanner.style.display = warningBanner.children.length ? 'block' : 'none';
        }
        var div = document.createElement('div');
        div.innerHTML = msg;
        warningBanner.appendChild(div);
        if (type == 'error') div.style = 'background: red; padding: 10px;';
        else {
          if (type == 'warning') div.style = 'background: yellow; padding: 10px;';
          setTimeout(function() {
            warningBanner.removeChild(div);
            updateBannerVisibility();
          }, 5000);
        }
        updateBannerVisibility();
      }

      var buildUrl = "Build";
      var loaderUrl = buildUrl + "/test_sftp.loader.js";
      var config = {
        dataUrl: buildUrl + "/test_sftp.data.unityweb",
        frameworkUrl: buildUrl + "/test_sftp.framework.js.unityweb",
        codeUrl: buildUrl + "/test_sftp.wasm.unityweb",
        streamingAssetsUrl: "StreamingAssets",
        companyName: "DefaultCompany",
        productName: "catchthechick",
        productVersion: "1.0",
        showBanner: unityShowBanner,
      };

      // By default Unity keeps WebGL canvas render target size matched with
      // the DOM size of the canvas element (scaled by window.devicePixelRatio)
      // Set this to false if you want to decouple this synchronization from
      // happening inside the engine, and you would instead like to size up
      // the canvas DOM size and WebGL render target sizes yourself.
      // config.matchWebGLToCanvasSize = false;

      if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent) || true) {
        // Mobile device style: fill the whole browser client area with the game canvas:

        var meta = document.createElement('meta');
        meta.name = 'viewport';
        meta.content = 'width=device-width, height=device-height, initial-scale=1.0, user-scalable=no, shrink-to-fit=yes';
        document.getElementsByTagName('head')[0].appendChild(meta);
        container.className = "unity-mobile";

        // To lower canvas resolution on mobile devices to gain some
        // performance, uncomment the following line:
        // config.devicePixelRatio = 1;

        canvas.style.width = window.innerWidth + 'px';
        canvas.style.height = window.innerHeight + 'px';
      } else {
        // Desktop style: Render the game canvas in a window that can be maximized to fullscreen:

        canvas.style.width = "1080px";
        canvas.style.height = "2400px";
      }

      loadingBar.style.display = "block";

      var script = document.createElement("script");
      script.src = loaderUrl;
      script.onload = () => {
        createUnityInstance(canvas, config, (progress) => {
          progressBarFull.style.width = 100 * progress + "%";
        }).then((unityInstance) => {
          gameInstance = unityInstance;
          loadingBar.style.display = "none";
          fullscreenButton.onclick = () => {
            unityInstance.SetFullscreen(1);
          };
        }).catch((message) => {
          alert(message);
        });
      };
      document.body.appendChild(script);

      document.addEventListener('DOMContentLoaded', () => {
          // 查找并移除具有特定 ID 的元素
          const element = document.getElementById('ton-connect');
          if (element) {
              element.remove(); // 或 element.parentNode.removeChild(element);
          }
      });
    
      var shakeThreshold = 15;  // 设置摇晃阈值
      var lastTime = 0;
      var lastX = 0, lastY = 0, lastZ = 0;

      // 检测摇晃的处理函数
      function detectShake(event) {
          var currentTime = new Date().getTime();
          if ((currentTime - lastTime) > 100) {  // 每100ms检测一次
              var acceleration = event.accelerationIncludingGravity;
              var deltaX = acceleration.x - lastX;
              var deltaY = acceleration.y - lastY;
              var deltaZ = acceleration.z - lastZ;
              var spe_value = Math.abs(deltaX) + Math.abs(deltaY) + Math.abs(deltaZ)
              if (spe_value > shakeThreshold) {
                  // 向 Unity 发送消息
                  var str_data = deltaX + ',' + deltaY + ',' + deltaZ;
                  gameInstance.SendMessage('ShakeEvent', 'OnShakeDetected', str_data);
                  //console.log('shake!!!')
              }

              lastTime = currentTime;
              lastX = acceleration.x;
              lastY = acceleration.y;
              lastZ = acceleration.z;
          }
      }

      //移动端控制台
      // window.onload = function() {
      //   var vConsole = new VConsole();
      // };
    </script>

    <script async src="https://www.googletagmanager.com/gtag/js?id=G-L7ZV2M304C"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-L7ZV2M304C');
    </script>


    <script>
      // 使用一个全局变量存储 AdController
      var adController = null;

      // 初始化 AdsGram 广告
      function initAdsgram() {
          if (typeof window.Adsgram !== 'undefined') {
              adController = window.Adsgram.init({ blockId: 'int-5424' });
              console.error("AdsGram is init successfully");
          } else {
              console.error("AdsGram is not init properly");
              //setTimeout(initAdsgram, 500);  // 延迟500毫秒执行初始化
          }
      }

      // 在页面加载完成时初始化 AdsGram
      window.onload = function () {
          initAdsgram();
          //setTimeout(initAdsgram, 500);  // 延迟500毫秒执行初始化
      };

      // 展示广告并处理奖励逻辑（被 Unity 调用的函数）
      function ShowAdAndReward() {
          if (adController) {
              adController.show().then((result) => {
                  if (result.done) {
                      // 用户观看广告并完成
                      gameInstance.SendMessage('BuyEquip', 'ProAdsReward');
                      console.log('奖励用户道具');
                  } else {
                      // 用户未观看广告到最后
                      gameInstance.SendMessage('BuyEquip', 'ProAdsSkip');
                      console.log('未完成道具广告');
                  }
              }).catch((error) => {
                  // 错误处理
                  console.log('广告播放出错', error);
              });
          } else {
              console.error("AdController is not initialized properly");
          }
      }

      function ShowAdAndGameStart() {
          if (adController) {
              adController.show().then((result) => {
                  if (result.done) {
                      // 用户观看广告并完成
                      gameInstance.SendMessage('Main', 'GameAdsReward');
                      console.log('奖励用户游戏开始');
                  } else {
                      // 用户未观看广告到最后
                      gameInstance.SendMessage('Main', 'GameAdsSkip');
                      console.log('未完成游戏开始广告');
                  }
              }).catch((error) => {
                  // 错误处理
                  gameInstance.SendMessage('Main', 'ResetIsReqGameStart');
                  console.log('广告播放出错', error);
              });
          } else {
              console.error("AdController is not initialized properly");
          }
      }
    </script>


  </body>
</html>
